<?php
/*
 * @Date: 2024-04-11 15:16:57
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-04-28 13:33:26
 * 
 * config/process.php 添加两个配置 task 处理长任务，websocket提供长连接服务
 * task 通过nginx代理 location /admin/system/long_task/
 * 
 * 'task' => [
        'handler' => \Webman\App::class,
        'listen' => 'http://0.0.0.0:8788',
        'count' => 2, // 进程数
        'user' => '',
        'group' => '',
        'reusePort' => true,
        'constructor' => [
            'request_class' => \support\Request::class, // request类设置
            'logger' => \support\Log::channel('default'), // 日志实例
            'app_path' => app_path(), // app目录位置
            'public_path' => public_path() // public目录位置
        ]
    ],
    'websocket' => [
        'handler' => process\WebsocketEven.php::class,
        'listen'  => 'websocket://0.0.0.0:8800',
        'count'   => 1,
    ]
 */


namespace process;

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Ldy\LdyWebsocket;
use Workerman\Timer;

class WebsocketEven
{
    // protected $worker;

    protected $request = [];


    public function onWorkerStart(Worker $worker)
    {
        
    }

    public function onConnect(TcpConnection $connection)
    {
        // echo "onConnect-".$connection->id."\n";
    }



    public function onWebSocketConnect(TcpConnection $connection, $http_buffer)
    {
        $request = new Request($http_buffer);
        $this->request[$connection->id] = $request;

        //检查是否登录成功
        $isLogin = check_token($request);
        
        if(!$isLogin) {
            $connection->send(LdyWebsocket::encodeData("not_login"));
            Timer::add(1,function($connection) {
                $connection->close();
            },[$connection], false);
        }
    }

    public function onMessage(TcpConnection $connection, $data)
    {
        $res = json_decode($data,true);
        $request = $this->request[$connection->id];

        LdyWebsocket::onMessage($connection,$res, $request);
        
        // print_r($request->session()->get('admin')['name']."\n");
    }

    public function onClose(TcpConnection $connection)
    {
        if(isset($this->request[$connection->id])) unset($this->request[$connection->id]);
    }

}
